/**
 * @constructor 编辑库名称
 */
import React from 'react';
import { Form, Input, Field, Overlay, Balloon } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import debounce from 'lodash.debounce';
import { checkProjectName } from 'api/index.js';
import './overlay.scss';
import intl from '../../locale';

const { organization } = window.FORCE;

const prefix = 'new-import-name';
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

export default class TableCellOverlay extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      visible: false,
    };

    this.field = new Field(this);
    this.checkPathDelay = debounce(this.checkPath, 500);
  }

  componentDidMount() {
    if (this.props.isRepeat) {
      this.field.setError(
        'name',
        intl.get({
          id: 'code-assets.components.importProjectListModal.overlay.DuplicateNameExistsModify',
          defaultMessage: '存在重名，请修改',
        }),
      );
    }
    if (this.props.isInvalidate) {
      this.field.setError(
        'name',
        intl.get({
          id: 'code-assets.src.utils.locale.ItCanOnlyContainLetters',
          defaultMessage: "只能包含字母和数字、 '_'、 '.'和'-'，且只能以字母、数字或'_'开头",
        }),
      );
    }
  }

  componentDidUpdate(prevProps, prevState) {
    if (!prevState.visible && this.state.visible) {
      const { value, import_repo_id } = this.props;
      try {
        document
          .querySelector(`.${prefix}-textarea-${import_repo_id} textarea`)
          .setSelectionRange(value.length, value.length);
      } catch (e) {
        console.error(e);
      }
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.isRepeat && !this.props.isRepeat) {
      this.field.setError(
        'name',
        intl.get({
          id: 'code-assets.components.importProjectListModal.overlay.DuplicateNameExistsModify',
          defaultMessage: '存在重名，请修改',
        }),
      );
    }
    if (nextProps.isInvalidate && !this.props.isInvalidate) {
      this.field.setError(
        'name',
        intl.get({
          id: 'code-assets.src.utils.locale.ItCanOnlyContainLetters',
          defaultMessage: "只能包含字母和数字、 '_'、 '.'和'-'，且只能以字母、数字或'_'开头",
        }),
      );
    }
  }

  onClick = () => {
    const { visible } = this.state;
    this.setState({
      visible: !visible,
    });
  };

  onClose = () => {
    this.checkPath(this.field.getValue('name'), (error) => {
      if (!error) {
        const value = this.field.getValue('name');
        this.props.saveName(value, this.props.import_repo_id);
      }
      this.setState({
        visible: false,
      });
    });
  };

  onVisibleChange = (visible) => {
    this.setState({
      visible,
    });
  };

  pathValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (/^[a-zA-Z0-9_.][a-zA-Z0-9_.-]{0,}$/.test(value)) {
      this.checkPathDelay(value, callback);
    } else {
      callback(
        intl.get({
          id: 'code-assets.src.utils.locale.ItCanOnlyContainLetters',
          defaultMessage: "只能包含字母和数字、 '_'、 '.'和'-'，且只能以字母、数字或'_'开头",
        }),
      );
    }
  };

  checkPath = (value, callback) => {
    let namespace_id = this.field.getValue('namespace_id');
    if (!Number(namespace_id)) {
      namespace_id = organization.namespace_id || '';
    }

    checkProjectName({ path: value, name: value, namespace_id })
      .then(() => {
        callback();
      })
      .catch(() => {
        callback(
          intl.get({
            id: 'code-assets.components.importProjectListModal.overlay.DuplicateNameExistsModify',
            defaultMessage: '存在重名，请修改',
          }),
        );
      });
  };

  onKeyDown = (e) => {
    if (e.keyCode === 13) {
      this.onClose();
    }
  };

  render() {
    const { isRepeat, isInvalidate, value, import_repo_id } = this.props;

    const { init } = this.field;
    let errorText;
    if (isRepeat) {
      errorText = intl.get({
        id: 'code-assets.components.importProjectListModal.overlay.DuplicateName',
        defaultMessage: '重名',
      });
    } else if (isInvalidate) {
      errorText = intl.get({
        id: 'code-assets.components.importProjectListModal.overlay.Illegal',
        defaultMessage: '非法',
      });
    } else {
      errorText = '';
    }
    return (
      <div>
        <div
          className={`${prefix}-cell`}
          ref={(ref) => {
            this.target = ref;
          }}
        >
          <div
            className={`${prefix}-cell-body ${isRepeat || isInvalidate ? 'has-error' : ''}`}
            onClick={this.onClick}
            ref={(ref) => {
              this.btn = ref;
            }}
          >
            <Balloon.Tooltip
              trigger={<span className={`${prefix}-cell-info one-line-ellipsis`}>{value}</span>}
              align="t"
            >
              {value}
            </Balloon.Tooltip>
            <YunxiaoIcon className="edit-name-icon" type="edit-line" />
          </div>
          <div
            className={`${prefix}-cell-help`}
            style={{ display: isRepeat || isInvalidate ? 'block' : 'none' }}
          >
            <YunxiaoIcon type="delete-fill" /> {errorText}
          </div>
        </div>
        <Overlay
          visible={this.state.visible}
          target={() => this.target}
          safeNode={() => this.btn}
          followTrigger
          container={this.target}
          onRequestClose={this.onClose}
        >
          <div
            className={`${prefix}-edit-area overlay-shadow ${
              this.field.getError('name') ? 'has-error' : ''
            }`}
          >
            <Form {...formItemLayout} field={this.field} labelAlign="top">
              <FormItem label="">
                <Input.TextArea
                  autoHeight
                  trim
                  autoFocus
                  className={`${prefix}-textarea ${prefix}-textarea-${import_repo_id}`}
                  onKeyDown={this.onKeyDown}
                  {...init('name', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.components.importProjectListModal.overlay.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },

                      {
                        validator: this.pathValidator,
                      },
                    ],

                    initValue: value,
                  })}
                />
              </FormItem>
            </Form>
          </div>
        </Overlay>
      </div>
    );
  }
}
